<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Jalan_periode extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('flexigrid');
        $this->load->library('flexigrid');
		$this->load->library('session');
		$this->load->library('form_validation');
        $this->load->model('jalan_periode_model');
        $this->load->model('jalan_model');
        $this->load->model('keping_model');
        $this->load->model('periode_model');
        $this->load->model('kelas_santri_model');
    }

//end Main
    //load Grid
    function index($id_periode) {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
			$this->session->set_userdata('id_periode', $id_periode);
            $colModel['no'] = array('No', 30, TRUE, 'center', 0);
            $colModel['NO_RUAS'] = array('No Ruas Jalan', 200, TRUE, 'center', 1);
            $colModel['NAMA_RUAS_JALAN'] = array('Nama Ruas Jalan', 200, TRUE, 'center', 1);
            $colModel['PANJANG'] = array('Panjang', 150, TRUE, 'center', 1);
			$colModel['Kelola_Ruas_Jalan'] = array('Kelola Ruas Jalan', 100, TRUE, 'center', 0);
			
			
			//get_periode_name
			$periode = $this->periode_model->selectone($id_periode);
			foreach ($periode->result() as $row) {
                $nama_periode = $row->NAMA_PERIODE;
                $mulai = $row->MULAI;
                $selesai = $row->SELESAI;
            }
			$this->session->set_userdata('nama_periode', $nama_periode);
			$this->session->set_userdata('mulai', $mulai);
			$this->session->set_userdata('selesai', $selesai);


            $gridParams = array(
                'width' => 'auto',
                'height' => 350,
                'rp' => 10,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
                'title' => 'Daftar Ruas Jalan</br>Periode : '.$nama_periode,
                'showTableToggleBtn' => true
            );

			$buttons[] = array('Tambah', 'add', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('Hapus', 'delete', 'spt_js');
			$buttons[] = array('separator');
            $buttons[] = array('Import', 'import', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('Kembali ke daftar periode', 'back', 'spt_js');


            // mengambil data dari file controler ajax pada method grid_berkas
            $grid_js = build_grid_js('flex1', site_url("jalan_periode/grid/".$id_periode.""), $colModel, 'NO_RUAS', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
		function spt_js(com,grid)
		{
			if (com=='Tambah')
			{
				location.href='" . base_url() . "index.php/jalan_periode/daftar_jalan';
			}
			
			if (com=='Import')
			{
				location.href='" . base_url() . "index.php/jalan_periode/form_import';
			}
			
			if (com=='Kembali ke daftar periode')
			{
				location.href='" . base_url() . "index.php/periode';
			}

			if (com=='Hapus')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin menghapus ' + $('.trSelected',grid).length + ' jalan?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '" . base_url() . "index.php/jalan_periode/delete" . "',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
							   }
							});
						}
					} else {
						return false;
					}
				}

		}
		</script>
		";


            $data['js_grid'] = $grid_js;

            //rendering view
            //$data['title'] = 'Daftar Peserta';
            //$data['js_grid']=$grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid($id_periode) {
        $valid_fields = array('ID_JALAN_PERIODE', 'NAMA_RUAS_JALAN', 'PANJANG');
        $this->flexigrid->validate_post('jalan_periode.NO_RUAS', 'asc', $valid_fields);
        $records = $this->jalan_periode_model->get_data($id_periode);
        $this->output->set_header($this->config->item('json_header'));

        $no = 0;
        foreach ($records['records']->result() as $row) {
		
            $record_items[] = array(
                $row->ID_JALAN_PERIODE,
                $no = $no + 1,
                $row->NO_RUAS,
				$row->NAMA_RUAS_JALAN,
                number_format($row->PANJANG, null, ',', '.').' meter',
                '<a href=\'' . base_url() . 'index.php/keping/index/' . $row->NO_RUAS . '\'><img border=\'0\' src=\'' . base_url() . 'public/images/setting.png\'></a> '
            );
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }

	
    function form_import(){
        if ($this->session->userdata('username') == NULL){
            redirect('login');
        } else {
            $data['status'] = 'new';
            $data['failed'] = false;
            $data['aa'] = '';
			//$data['ustad'] = $this->ustad_model->get_data_all_ustad();
            $data['content'] = $this->load->view('form_import', $data, true);
            $this->load->view('main', $data);
        }
    }

	
    function import() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            if ($this->cek_validasi() != FALSE) {
                $this->form();
            } else {
                $field_name = 'import_data';
                $config['upload_path'] = "file/importdata";
                $config['allowed_types'] = '*';
                //$config['allowed_types'] ='jpg';
				
				//create folder
				if(!is_dir($config['upload_path'])){
					mkdir($config['upload_path'], 0777);
					//mkdir($config['upload_path2'], 0777);
				}

                $this->load->library('upload', $config);
                $files = $this->upload->do_upload($field_name);

                    $data = $this->upload->data($field_name); //get file_name
                    
					if (!$files) {
						$this->form_upload();
						}
					else {
						$file_name = $data['file_name'];
						}
					
                    $path[0] = 'file/importdata/' . $file_name;
                    $path[1] = $file_name;
                    //return $path;
					
					$this->load->library('csvreader');
					$result =   $this->csvreader->parse_file($path[0]);

					$data['csvData'] =  $result;
					//$this->load->view('view_csv', $data);  
					
					
					//save imported data to database
					$keping_jalan = 1;
					foreach($result as $field){
						$posisi_km = ($field['KMPOST']*10)+$field['OFFSETFR'];
						$data2 = array(
							'KEPING' => $keping_jalan,
							'NO_RUAS' => $field['RUAS'],
							'POSISI_KM' => $posisi_km,
							'NILAI_IRI' => $field['IRI'],
							'ID_PERIODE' => $this->session->userdata('id_periode')
						);
						$this->keping_model->insert($data2);
						$keping_jalan++;
					}
					//$this->load->view('view_csv', $data);  
					
					$data['failed'] = false;
					$data['aa'] = '';
					$data['content'] = $this->load->view('import_succes', $data, true);
					$this->load->view('main', $data);

                    // $data = array(
                        // 'NPK' => $this->input->post('NPK'),
						// 'nama_ustad' => $this->input->post('nama_ustad'),
                        // 'alamat_ustad' => $this->input->post('alamat_ustad'),
                        // 'telp_flexi' => $this->input->post('telp_flexi'),
                        // 'telp_rumah' => $this->input->post('telp_rumah'),
                        // 'foto_ustad' => $path[0]
                    // );
					// $data = str_replace("'", "\'", $data);
                    // $this->ustad_model->insert($data);
                    // redirect('ustad');
                }
            }
        }

	
	//test
	function readcvs()
	{
        $this->load->library('csvreader');
        $result =   $this->csvreader->parse_file('tes.csv');

        $data['csvData'] =  $result;
        $this->load->view('view_csv', $data);  
	}
	
	
	
    //----ADD MULTIPLE RUAS JALAN----//
	function daftar_jalan() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
			$colModel['no'] = array('No', 30, TRUE, 'center', 0);
            $colModel['NO_RUAS'] = array('No Ruas Jalan', 100, TRUE, 'center', 1);
            $colModel['NAMA_RUAS_JALAN'] = array('Nama Ruas Jalan', 200, TRUE, 'center', 1);
            $colModel['PANJANG'] = array('Panjang', 150, TRUE, 'center', 1);
            $colModel['STATUS'] = array('Status', 100, TRUE, 'center', 1);
			
			
			$gridParams = array(
                'width' => 'auto',
                'height' => 350,
                'rp' => 10,
                'rpOptions' => '[5,10,15,20,25,40]',
                'pagestat' => 'Menampilkan: {from} hingga {to} dari {total} data.',
                'blockOpacity' => 0.5,
                'title' => 'Daftar Master Ruas Jalan',
                'showTableToggleBtn' => true
            );

            $buttons[] = array('Tambahkan Ruas Jalan', 'add', 'spt_js');
            $buttons[] = array('separator');
            $buttons[] = array('Kembali', 'back', 'spt_js');
			// $buttons[] = array('separator');
            // $buttons[] = array('Hapus', 'delete', 'spt_js');
		

            // mengambil data dari file controler ajax pada method grid_berkas
            $grid_js = build_grid_js('flex1', site_url("jalan_periode/grid_add/"), $colModel, 'NO_RUAS', 'asc', $gridParams, $buttons);

            $data['added_js'] =
                    "<script type='text/javascript'>
		function spt_js(com,grid)
		{
			if (com=='Kembali')
			{
				location.href='" . base_url() . "index.php/jalan_periode/index/".$this->session->userdata('id_periode')."';
			}

			if (com=='Tambahkan Ruas Jalan')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin menambah ' + $('.trSelected',grid).length + ' data ruas jalan?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '" . base_url() . "index.php/jalan_periode/add" . "',
							   data: 'items='+itemlist,
							   success: function(data){
								alert(data);
								window.location.href = '" . base_url() . "index.php/jalan_periode/index/".$this->session->userdata('id_periode')."';
							   }
							});
						}
					} else {
						return false;
					}
				}
				
				

		}
		</script>
		";


            $data['js_grid'] = $grid_js;

            //rendering view
            //$data['title'] = 'Daftar Peserta';
            //$data['js_grid']=$grid_js;
            $data['content'] = $this->load->view('grid', $data, true);
            $this->load->view('main', $data);
        }
    }

    function grid_add() {
        $valid_fields = array('NO_RUAS', 'NAMA_RUAS_JALAN', 'PANJANG');
        $this->flexigrid->validate_post('NO_RUAS', 'asc', $valid_fields);
        $records = $this->jalan_model->get_data();
        $this->output->set_header($this->config->item('json_header'));

        $no = 0;
        foreach ($records['records']->result() as $row) {
			if($row->STATUS == 1){
				$status = 'Aktif';
			}
			else $status = 'Tidak Aktif';
			
            $record_items[] = array(
                $row->NO_RUAS,
                $no = $no + 1,
                $row->NO_RUAS,
				$row->NAMA_RUAS_JALAN,
                number_format($row->PANJANG, null, ',', '.').' meter',
				$status
            );
        }

        if (isset($record_items))
            $this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));
        else
            $this->output->set_output('{"page":"1","total":"0","rows":[]}');
    }

    
    function add() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $spt_ids_post_array = explode(",", $this->input->post('items'));
            foreach ($spt_ids_post_array as $index => $id) {
                if (isset($id) && $id != '') {
					$data = array(
						'ID_PERIODE' => $this->session->userdata('id_periode'),
						'NO_RUAS' => $id
					);
					$msg ='Data ruas jalan berhasil ditambahkan.';
					$this->jalan_periode_model->insert($data);
					$this->output->set_header($this->config->item('ajax_header'));
					$this->output->set_output($msg);
                }//end if
            }//end foreach
        }
    }
	
	
	function delete() {
        if ($this->session->userdata('username') == NULL) {
            redirect('login');
        } else {
            $spt_ids_post_array = explode(",", $this->input->post('items'));
  
            foreach ($spt_ids_post_array as $index => $id) {
                if (isset($id) && $id != '') {
                    $this->jalan_periode_model->delete($id);
                }//end if
            }//end foreach
        }
    }
	
	
	function cek_validasi() {
        // Setting Rules
        $this->form_validation->set_rules('no_ruas', 'No Ruas Jalan', 'required|numeric|greater_than[0]');
        $this->form_validation->set_rules('nama_ruas', 'Nama Ruas Jalan', 'required');
        $this->form_validation->set_rules('panjang', 'Panjang Jalan', 'required|numeric|greater_than[0]');
        //$this->form_validation->set_rules('tgl_selesai', 'Tanggal Selesai', 'required');
		
		
        //Setting Error Message
        $this->form_validation->set_message('required', 'Field %s harus diisi.');
        $this->form_validation->set_message('numeric', 'Field %s harus diisi angka.');
		$this->form_validation->set_message('greater_than', 'Field %s harus diisi angka lebih dari 0');


        // Setting Delimiter
        $this->form_validation->set_error_delimiters('<li class="error">', '</li>');
        return $this->form_validation->run();
    }

}

//end class

/* End of file welcome.php */
/* Location: ./system/application/controllers/main.php */
